package com.yanyeori.webtest.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yanyeori.framework.core.util.StringUtil;
import com.yanyeori.framework.datasource.annotation.DataSource;
import com.yanyeori.framework.security.event.LoginEvent;
import com.yanyeori.webtest.bo.LoginLogBO;
import com.yanyeori.webtest.entity.yanye.LoginLogEntity;
import com.yanyeori.webtest.mapper.LoginLogMapper;
import com.yanyeori.webtest.mapstruct.LoginLogStructMapper;
import com.yanyeori.webtest.service.LoginLogService;
import org.springframework.context.event.EventListener;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 登录日志service
 *
 * @author chenkuan
 * @since 2021/8/10 010 9:43
 */
@DataSource("yanye-mysql")
@Service
public class LoginLogServiceImpl extends ServiceImpl<LoginLogMapper, LoginLogEntity> implements LoginLogService {

    @Override
    public List<LoginLogBO> listLoginLog(LoginLogBO loginLogBO) {
        List<LoginLogEntity> list = lambdaQuery()
                .eq(StringUtil.isNotEmpty(loginLogBO.getLoginIp()), LoginLogEntity::getLoginIp, loginLogBO.getLoginIp())
                .eq(StringUtil.isNotEmpty(loginLogBO.getUserId()), LoginLogEntity::getUserId, loginLogBO.getUserId())
                .eq(StringUtil.isNotEmpty(loginLogBO.getUsername()), LoginLogEntity::getUsername, loginLogBO.getUsername())
                .eq(loginLogBO.getLoginTime() != null, LoginLogEntity::getLoginTime, loginLogBO.getLoginTime())
                .orderByDesc(LoginLogEntity::getLoginTime)
                .list();
        return LoginLogStructMapper.INSTANCE.entityListToBOList(list);
    }

    /**
     * 监听登录成功事件，插入登录日志
     */
    @Async
    @EventListener
    public void listener(LoginEvent loginEvent) {
        LoginLogEntity entity = new LoginLogEntity();
        entity.setUserId(loginEvent.getUserId());
        entity.setUsername(loginEvent.getUsername());
        entity.setLoginIp(loginEvent.getLoginIp());
        entity.setChannel(loginEvent.getChannel());
        entity.setLoginTime(System.currentTimeMillis());
        save(entity);
    }
}
